#include "mytablemodel.h"
#include <QDebug>
#include <QSqlDriver>
#include <QSqlError>
#include <QSqlRecord>
#include <qmath.h>
#include <QDateTime>

//QSqlQuery* myTableModel::m_query =new QSqlQuery(QSqlDatabase::database("qt_sql_default_connection"));
//QVector<QString> myTableModel::m_tableTitle;
//QString myTableModel::queryser;



myTableModel::myTableModel(QSqlQueryModel* parent)
    :QSqlQueryModel(parent), m_tableName("weightTable")
    , m_query(new QSqlQuery(QSqlDatabase::database("qt_sql_default_connection")))
{
    QDateTime dateTime= QDateTime::currentDateTime();
    m_startTime = dateTime.toString("yyyy-MM-dd 00:00:00");
    m_endTime = dateTime.toString("yyyy-MM-dd 23:59:59");
    m_roleNames[Qt::DisplayRole] = "value";
    m_roleNames[Qt::EditRole] = "edit";

    //connect(this,&myTableModel::startTimeChanged,this,&myTableModel::slotStartTimeChanged);
    //connect(this,&myTableModel::endTimeChanged,this,&myTableModel::slotEndTimeChanged);
    connect(this,&myTableModel::currentPageChanged,this,&myTableModel::slotCurrentPageChanged);
}

myTableModel::~myTableModel()
{
    //m_db.close();
    delete m_query;
    m_query = nullptr;
}

/*override.
*/
QVariant myTableModel::data(const QModelIndex &index, int role) const
{
    //m_db.open();
    QVariant v;
    // the index returns the requested row and column information.
    int row = index.row();
    int column = index.column();

    // boundary check for the row and column
    if(row < 0 || row >= this->rowCount()
        ||column < 0 || column >= this->columnCount())
    {
        //m_db.close();
        return v;
    }
    if (role & ~(Qt::DisplayRole | Qt::EditRole))
    {
        //m_db.close();
        return v;
    }
    qDebug()<<m_query->at();    //C 用于获取当前查询“结果集”中当前记录的索引位置。
    qDebug()<<"row :"<<row<<"colum: "<<column<<"role: "<<role;

    m_query->seek(row);         //C 用于将查询结果集的游标（cursor）移动到指定行，以便访问该行的数据。
    qDebug()<<m_query->value(column);       //C m_query只返回1个值吗？
    QVariant res = m_query->value(column);
    //m_query->finish();
    //m_db.close();
    return res;

}

QHash<int, QByteArray> myTableModel::roleNames() const
{
    return m_roleNames;
}

QString myTableModel::tableName() const
{
    return m_tableName;
}

void myTableModel::setTableName(const QString _tableName)
{
    if(_tableName != m_tableName )
    {
        m_tableName = _tableName;
        emit tableNameChanged();
    }

}

QString myTableModel::startTime()
{
    return m_startTime;
}

void myTableModel::setStartTime(QString startTime)
{
    m_startTime=startTime;
    emit startTimeChanged(m_startTime);
}

QString myTableModel::endTime()
{
    return m_endTime;
}

void myTableModel::setEndTime(QString endTime)
{
    m_endTime=endTime;
    emit endTimeChanged(m_endTime);
}

int myTableModel::currentPage()
{
    return m_currentPage;
}

void myTableModel::setCurrentPage(int currentPage)
{
    m_currentPage = currentPage;
    emit currentPageChanged(m_currentPage);
}
QVariant myTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{//这个函数获取表头数据
    if(role != Qt::DisplayRole)
        return QVariant();
    if(orientation == Qt::Horizontal)
    {
        return m_tableTitle.at(section);
    }
    else if(orientation == Qt::Vertical)
    {
        return QString::number(section);
    }
    return QVariant();
}
int myTableModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
//    QString queryser= QString("select "
//                       "weight, createdTime "
//                       "from "
//                       "weightTable");
    //m_query->exec(queryser);
    //m_db.open();
    if(!(QSqlDatabase::database("qt_sql_default_connection")).isOpen()){
        QSqlDatabase::database("qt_sql_default_connection").open();
    }
    m_query->exec(queryser);
    int rowCount = 0;
    if(m_query->last())
    {
        rowCount =  m_query->at() + 1;
        m_query->first();
        m_query->previous();
    }
    //m_query->finish();
    //m_db.close();
    return rowCount;
}
int myTableModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return m_query->record().count();
}
void myTableModel::refresh()
{
//    QString queryser= QString("select "
//                               "weight, createdTime "
//                               "from "
//                               "weightTable");
    if(!(QSqlDatabase::database("qt_sql_default_connection")).isOpen()){
        QSqlDatabase::database("qt_sql_default_connection").open();
    }
    m_query->exec(queryser);
    //m_query->finish();
}

void myTableModel::slotTimeChanged(QString startTime, QString endTime)
{

    if(m_currentPage<0)
    {
        return;
    }
    //m_db.open();
    if(startTime.length()>0&&endTime.length()>0){

        queryser= QString("select "
                           "createdTime, weight||weightUnit as strWeight, angle "
                           "from "
                           "weightTable where createdTime >= '%1' "
                           "and createdTime <= '%2' order by createdTime "
                           "limit 9 offset %3;")
                        .arg(startTime)
                        .arg(endTime)
                        .arg(m_currentPage*9);
    }
    else
    {
        queryser= QString("select "
                           "createdTime, weight||weightUnit as strWeight, angle "
                           "from "
                           "weightTable order by createdTime "
                           "limit 9 offset %1;")
                           .arg(m_currentPage*9);
    }
    //m_query->clear();
    if(!(QSqlDatabase::database("qt_sql_default_connection")).isOpen()){
        QSqlDatabase::database("qt_sql_default_connection").open();
    }
    if(!m_query->exec(queryser))
        qDebug()<<m_query->lastError();

    this->setQuery(*m_query);

    int columns = this->columnCount();
    m_tableTitle.clear();
    for(int i = 0; i < columns; ++i)
    {
        m_tableTitle.append(m_query->record().fieldName(i));//获取字段名
    }
    //m_db.close();
    //m_query->finish();
}

void myTableModel::slotStartTimeChanged(QString startTime)
{
    slotTimeChanged(startTime,m_endTime);
}

void myTableModel::slotEndTimeChanged(QString endTime)
{
    slotTimeChanged(m_startTime,endTime);
}

void myTableModel::slotCurrentPageChanged(int currentPage)
{
    if(currentPage<0)
    {
        return;
    }
    //m_db.open();
    if(m_startTime.length()>0&&m_endTime.length()>0){

        queryser= QString("select "
                           "createdTime, weight||weightUnit as strWeight, angle "
                           "from "
                           "weightTable where createdTime >= '%1' "
                           "and createdTime <= '%2' order by createdTime "
                           "limit 9 offset %3;")
                       .arg(m_startTime)
                       .arg(m_endTime)
                       .arg(currentPage*9);     //C 每页9个记录。
    }
    else
    {
        queryser= QString("select "
                           "createdTime, weight||weightUnit as strWeight, angle "
                           "from "
                           "weightTable order by createdTime "
                           "limit 9 offset %1;")
                       .arg(currentPage*9);
    }
    //m_query->clear();
    if(!(QSqlDatabase::database("qt_sql_default_connection")).isOpen()){
        QSqlDatabase::database("qt_sql_default_connection").open();
    }
    if(!m_query->exec(queryser))
        qDebug()<<m_query->lastError();

    this->setQuery(*m_query);   //C 执行查询操作

    int columns = this->columnCount();  //C 行。
    m_tableTitle.clear();
    for(int i = 0; i < columns; ++i)
    {
        m_tableTitle.append(m_query->record().fieldName(i));//获取字段名
    }
    //m_db.close();
    //m_query->finish();
}

//void myTableModel::paraChanged(QString startTime, QString endTime, int currentPage, myTableModel& myTableModel)
//{
//    if(currentPage<0)
//    {
//        return;
//    }
//    //m_db.open();
//    if(startTime.length()>0&&endTime.length()>0){

//        queryser= QString("select "
//                           "createdTime, weight||weightUnit as strWeight, lon||lonDir as strLon, lat||latDir as strLat, height||heightUnit as strHeight "
//                           "from "
//                           "weightTable where createdTime >= '%1' "
//                           "and createdTime <= '%2' order by createdTime "
//                           "limit 9 offset %3;")
//                       .arg(startTime)
//                       .arg(endTime)
//                       .arg(currentPage*9);
//    }
//    else
//    {
//        queryser= QString("select "
//                           "createdTime, weight||weightUnit as strWeight, lon||lonDir as strLon, lat||latDir as strLat, height||heightUnit as strHeight "
//                           "from "
//                           "weightTable order by createdTime "
//                           "limit 9 offset %1;")
//                       .arg(currentPage*9);
//    }
//    qDebug()<<queryser;
//    //m_query->clear();
//    if(!(QSqlDatabase::database("qt_sql_default_connection")).isOpen()){
//        QSqlDatabase::database("qt_sql_default_connection").open();
//    }
//    if(!m_query->exec(queryser))
//        qDebug()<<m_query->lastError();

//    myTableModel.setQuery(*m_query);

//    int columns = myTableModel.columnCount();
//    m_tableTitle.clear();
//    for(int i = 0; i < columns; ++i)
//    {
//        m_tableTitle.append(m_query->record().fieldName(i));//获取字段名
//    }
//    //m_db.close();
//    //m_query->finish();
//}
//void myTableModel::slotParaChanged(QString startTime, QString endTime, int currentPage)
//{
//    myTableModel*  myNoStatic = new myTableModel();
//    paraChanged(startTime, endTime, currentPage, *myNoStatic);
//}
int myTableModel::totalCount()
{
    QString ser;
    if(m_startTime.length()>0&&m_endTime.length()>0){

        ser= QString("select "
                     "count(1) "
                     "from "
                     "weightTable where createdTime >= '%1' "
                     "and createdTime <= '%2' order by createdTime;")
                     .arg(m_startTime)
                     .arg(m_endTime);
    }
    else
    {
        ser= QString("select "
                     "count(1) "
                     "from "
                     "weightTable order by createdTime;");
    }
    QSqlQuery* query = new QSqlQuery(QSqlDatabase::database("qt_sql_default_connection"));
    query->exec(queryser);
    int rowCount = 0;
    if(query->next())
    {
        rowCount = qCeil(query->value(0).toInt()/9) ;
    }
    return rowCount;
}
